/**
 * 通讯录
 */
var dataList= new Array();

$(function(){
	
	
	initDeptList();//获取部门
	initList();//获取部门
	$("#dept-save").click(deptsave);
	$("#member-save").click(membersave);
	 //当文件变化的时候上传
	$("#uploadpic").change(uploadSpaceImage);
	$("#uploadpic2").change(uploadSpaceImage2);
    
    $("#btn_upload_save").click(btn_upload);
    $("#excel_icon_upload").click(function(){
    	$("#upload_file").click();
    })
    

     $("#upload_file").change(function(){
    	if(!$("#upload_file").val()){
    		alert("请选择要上传的文件！");
    		return;
    	}
    	var accessToken = localStorage.getItem('memberToken');

    	$('#upload').ajaxSubmit({
    		dataType : "json",
    		headers : {'Access-Control-Allow-Origin':'*',"token":accessToken},
    		beforeSubmit : function(request) { 
    			//alert("正在上传"); 
    		}, 
    		success : function(result, textStatus, response) { 
    			//alert(JSON.stringify(result));
    			if(result.status==0){    				
    				$("#excel_icon_upload").attr("data-path",result.data);
    				$("#upload_file_info").html("上传成功！");
    			}else{
    				$("#upload_file_info").tml(result.message);
    			}
    			 
    			//alert('成功上传！'); 		 
    		},
    		error : function(result) {
    			//alert('上传失败！'); 
    		} 
    	});
    })
})
 //上传excel模版文件
   
    
 function btn_upload (){

    	$path = $("#excel_icon_upload").attr("data-path");
    	if(!$path){
    		alert("请选择要上传的文件！");
    		return;
    	}

    	$.ajax({
            url: '/euc/center/member/batchImport',
            data:{"file_path":$path},
            beforeSend: function(request) {
            	var memberToken = localStorage.getItem('memberToken');
                request.setRequestHeader("token",memberToken );
            },
            async: true,
            contentType:'application/json;charset=utf-8',
            type: 'GET',
            success: function (result, textStatus, response) {
       			if(result.status==0){
       				alert("导入成功");
       				$('#MemberModal').modal('hide');
       				$("#excel_icon_upload").attr("data-path","");
       				
       			}else{
       				alert(result.message);
       			}
            },
            error: function () {
            	/*alert("error");*/
            }  
        });
    	
    	
    }



function membersave (){
	var requestJson = {};
	var idCard = $("input[name='idCard']").val();
    if(idCard == ''){
        alert("请输入身份证");
        return ;
    }
    requestJson["idCard"] = idCard;

    var member_id = $("#member-save").attr('data-id');
    if(member_id>0){
    	requestJson["id"]=member_id;
    }
    
    var userName = $("input[name='name']").val();
    if(userName == ''){
        alert("请输入姓名");
        return false;
    }
    requestJson["name"] = userName;

    var faceUrl = $("#addMemberModal #face_url").val();
    requestJson["faceUrl"] = faceUrl;

    var email = $.trim($("input[name='email']").val());
    if(email == ''){
        alert("请输入邮箱");
        return false;
    }
    requestJson["email"] = email;
    
    var dept_id = $("#dept_id").val();
    requestJson["deptId"] = dept_id;

    var mobile = $("#mobile").val();
    if(mobile == ''){
        alert("请输入电话号码");
        return false;
    }
    requestJson["mobile"] = mobile;
    $.ajax({
        url: '/euc/center/member/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var memberToken = localStorage.getItem('memberToken');
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
			if(result.status === 0){
				if(member_id>0){
					$("#add_title").val("新增会员");
					$("#member-save").removeAttr("data-id");
					$("#pwd").show();
					alert("修改成功");
					
				}else{
					alert("添加成功");	
				}
        		
        		$("#addMemberModal").modal('hide');
        		 window.location.reload();
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	console.log("error");
        }  
    });


}

function deptsave(){
	deptName=$("#deptName").val();
	if(!deptName){
		alert("请输入部门名称");return false;
	}
	$data ={"deptName":deptName,"parentId":0,"code":"anshu"};
	$.ajax({
        url: '/euc/center/member/addDept',
        data:JSON.stringify($data),
        beforeSend: function(request) {
        	var memberToken = localStorage.getItem('memberToken');
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
			if(result.status === 0){
        		alert("添加成功");
        		$("#addModal").modal('hide');
        		 window.location.reload();
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	console.log("error");
        }  
    });
	
}

function uploadSpaceImage(){
    $("#show_head").hide();
    var accessToken = localStorage.getItem('memberToken');
    $('#headForm').ajaxSubmit({
        dataType : "json",
        headers : {'Access-Control-Allow-Origin':'*',"token":accessToken},
        beforeSubmit : function(request) {
            //alert("正在上传");
        },
        success : function(result, textStatus, response) {
        	if(result.status===0){
        		$("#headImage").prop("src",result.data);
                $("#show_head").show();
                $("input[name='headImage']").val(result.data);
                $("#face_url").val(result.data);
                $("[formParameter='pic'][name='url']").val(result.data);
                $("#uploadpic").val("");
                alert(result.message);
        	}else{
        		alert(result.message);
        	}
            
            //alert('成功上传！');
        },
        error : function(result) {
            //alert('上传失败！');
            $("#show_head").hide();

        }
    });
}

function uploadSpaceImage2(){
    $("#show_head2").hide();
    var accessToken = localStorage.getItem('memberToken');
    $('#headForm2').ajaxSubmit({
        dataType : "json",
        headers : {'Access-Control-Allow-Origin':'*',"token":accessToken},
        beforeSubmit : function(request) {
            //alert("正在上传");
        },
        success : function(result, textStatus, response) {
        	if(result.status===0){
        		$("#headImage2").prop("src",result.data);
                $("#show_head2").show();
                $("input[name='headImage2']").val(result.data);
                $("#face_url2").val(result.data);
                $("[formParameter='pic'][name='url']").val(result.data);
                $("#uploadpic2").val("");
                $("#memberId").val("");
                alert(result.message);
        	}else{
        		alert(result.message);
        	}
            
            //alert('成功上传！');
        },
        error : function(result) {
            //alert('上传失败！');
            $("#show_head2").hide();

        }
    });
}
//删除部门
function delDept(id){
	deptId=parseInt(id);
	if(deptId>0){
		var data={"id":deptId};
		$.ajax({
	        url: '/euc/center/member/delDept',
	        data:data,
	        beforeSend: function(request) {
	        	var memberToken = localStorage.getItem('memberToken');
	            request.setRequestHeader("token",memberToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/x-www-form-urlencoded',
	        type: 'GET',
	        success: function (result, textStatus, response) {
	        	if(result.status === -2){
	        		gotoLogin();
	        	}
	        	//alert(JSON.stringify(result));
	    		if(result.status === 0){
	        		alert("删除成功");
	        		$name="#d"+deptId;
	        		$($name).remove();
	        		
	        	}else{
	        		alert(result.message);
	        	}
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	}
	
}
//获取部门
function initDeptList(){
	deptId = localStorage.getItem('memberDeptId');
	companyName = localStorage.getItem('memberCompanyName');
	isAdmin = parseInt(localStorage.getItem('memberAdmin'));
	if(!companyName) companyName='部门列表';
	$(".left_title").html(companyName);
	if(isAdmin==1){
		$(".left_button").html('<button type="button" data-target="#addModal" class="btn btn-default" data-backdrop="static" data-toggle="modal" style="background: #fff;color: #000;border:1px solid;">新增部门</button>');
	}

	$(".left_radios").html('<div class="radio"><label><input type="radio" name="optionsRadios" id="optionsRadios1" onclick="initList(0)" value="0">全部</label></div>');
	

	$.ajax({
        url: '/euc/center/member/list',
        data:'',
        beforeSend: function(request) {
        	var memberToken = localStorage.getItem('memberToken');
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/x-www-form-urlencoded',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	$.each(result,function(i,v){
        		html = '<div class="radio" id="d'+v.id+'"><label><input type="radio" name="optionsRadios" id="optionsRadios1" onclick="initList('+v.id+')" value="'+v.id+'">'+v.deptName+'</label>';
        		if(isAdmin==1){
        			html +=' <a class="cursor" onclick="delDept('+v.id+')">删除</a>';
        		}
        		html +='</div>';
        		$(".left_radios").append(html);
        		html2 ='<option value="'+v.id+'">'+v.deptName+'</option>'
        		$("#dept_id").append(html2);
        	})
        },
        error: function () {
        	console.log("error");
        }  
    });
}
//获用户
function initList(deptId){
	datajson = {};
	if(deptId){
		datajson = {"dept_id":deptId};
	}
	//deptId = localStorage.getItem('memberDeptId');
	isAdmin = parseInt(localStorage.getItem('memberAdmin'));

	if(isAdmin==1){
		$("#rightbtn").html('<button type="button" class="btn btn-default" data-target="#addMemberModal" data-backdrop="static" data-toggle="modal" style="background: #fff;color: #000;border:1px solid;margin-right:30px;">新增员工</button><button type="button" class="btn btn-default"data-target="#MemberModal" data-backdrop="static" data-toggle="modal" style="background: #fff;color: #000;border:1px solid;">导入员工</button>');
	}
	$.ajax({
		url: '/euc/_user/member_list',
		data:datajson,
		beforeSend: function(request) {
			var memberToken = localStorage.getItem('memberToken');
			request.setRequestHeader("token",memberToken );
		},
		dataType: 'JSON',
		async: true,
		contentType:'application/x-www-form-urlencoded',
		type: 'GET',
		success: function (result, textStatus, response) {
			//alert(JSON.stringify(result));
			if(result.status === -2){
        		gotoLogin();
        	}
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	
        	
        	$.each(result.data,function(i,data){
        		       		

        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' + data.member_name + '</td>';
        		html += '<td>' + data.mobile + '</td>';
        		html += '<td>' + (data.dept_name!=null ? data.dept_name : "无" ) + '</td>';
        		html += '<td>';
        		if(data.face_url){
                 	html += '<a href="javascript:view('+data.member_id+');" id="t'+data.member_id+'" data-url="'+data.face_url+'" class="tablelink">查看</a>';
        		}
        		if(isAdmin==1){
             		html += ' | <a href="javascript:upload('+data.member_id+');" class="tablelink">上传</a> ';
             		html += ' | <a href="javascript:edit('+data.member_id+');" class="tablelink">编辑</a>';
             	}
                 	html +='</td>';
        		
        		html += '</tr>';
        		dataList[data.member_id]=data;
	        	$("#userTable").append(html);
			});

		},
		error: function () {
			console.log("error");
		}  
	});
}
function view(id){
	$name='#t'+id;
	$src=$($name).attr('data-url');
	if(!$src){
		alert('头像为空');return false;
	}else{
		$("#head_url").attr('src',$src);
		$('#viewModal').modal('show');
	}
	
}
function upload(id){
		$("#memberId").val(id);
		$("#uploadpic2").val("");
		$('#uploadModal').modal('show');
	
}
function edit(id){
	data = dataList[id];
	$("#add_title").val("编辑会员");
	$("#member-save").attr("data-id",data.member_id);
	$("#pwd").hide();
	/*dept_id
	dept_name
	face_url

	member_id

	member_name
	mobile*/

	$("#addMemberModal #mobile").val(data.mobile);
	if(data.email) $("#addMemberModal #email").val(data.email);
	if(data.idCard) $("#addMemberModal #idCard").val(data.idCard);
	if(data.member_name) $("#addMemberModal #tname").val(data.member_name);
	if (data.dept_id > 0){
		$("#addMemberModal #dept_id").val(data.dept_id).trigger('change');		
	}
	if (data.face_url){
		$("#addMemberModal #show_head").show();
		$("#addMemberModal #headImage").attr('src',data.face_url);		
		$("#addMemberModal #face_url").val(data.face_url);		
	}
	

	$("#addMemberModal").modal({
			'backdrop':'static',
			'show':true
	});
	
}